package com.itfreer.http.request;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.itfreer.utils.JSONUtils;

/**
 * 定义可以带map参数的json对象post方法
 */
public class JsonObjectPostRequest extends Request<Map> {

    private Map<String,String> mMap;
    private Listener<Map>  mListener;

    public JsonObjectPostRequest(String url,
                                 Listener<Map> listener,
                                 ErrorListener errorListener,
                                 Map map) {
        super(Request.Method.POST, url, errorListener);
        mListener=listener;
        mMap = map;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mMap;
    }

    @Override
    protected Response<Map> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            Map resultMap = JSONUtils.toBean(jsonString, HashMap.class);
            return Response.success(resultMap, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (Exception e){
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(Map response) {
        mListener.onResponse(response);
    }
}